export default class WebSocketClient {
  constructor(userId, groupId,onMessageCallback) {
      this.userId = userId;
      this.groupId = groupId;
      this.socket = new WebSocket('ws://127.0.0.1:8080/websocket?userId=' + encodeURIComponent(userId));

    this.onMessageCallback = onMessageCallback;

      this.socket.onopen = this.onOpen.bind(this);
      this.socket.onmessage = this.onMessage.bind(this);
      this.socket.onerror = this.onError.bind(this);
      this.socket.onclose = this.onClose.bind(this);
  }

  onOpen() {
      // 发送用户 ID 和聊天组 ID 的集合
      const message = {
          type: 'connect',
          userId: this.userId,
          groupId: this.groupId,
      };
      this.socket.send(JSON.stringify(message));
  }

  sendMessage(message) {
      this.socket.send(JSON.stringify({
          type: 'message',
          userId: this.userId,
          groupId:this.groupId,   // todo
        ...message,
      }));
  }

  onMessage(event) {
      const data = JSON.parse(event.data);
      this.handleMessage(data);
     
  }

  handleMessage(data) {
      // 在这里处理接收到的消息，例如通过 Vuex 或其他状态管理库更新状态
      console.log('Received message is:', data);
      this.onMessageCallback(data); // 调用回调函数
  }

  onError(error) {
      console.error('WebSocket Error:', error);
  }

  onClose() {
      console.log('WebSocket Connection Closed');
  }
}